package com.yyx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.yyx.server.pojo.*;
import com.yyx.server.service.*;
import com.yyx.server.vo.PageVo;
import com.yyx.server.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import javassist.expr.NewArray;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YongXin
 * @since 2021-07-24
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private NationService nationService;
    @Autowired
    private PoliticsStatusService politicsStatusService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private JoblevelService joblevelService;
    @Autowired
    private PositionService positionService;
    @ApiOperation("分页搜索查询员工")
    @GetMapping("/")
    public PageVo getEmployee(@RequestParam(defaultValue = "1")Integer currentPage,
                                @RequestParam(defaultValue = "10")Integer pageSize,
                                Employee employee,
                                LocalDate[] dateScope){
        IPage<Employee> page = employeeService.getEmployeeByPage(currentPage, pageSize, employee, dateScope);
        return new PageVo(page.getTotal(),page.getRecords());
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNation(){
        return nationService.list();
    }
    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politics")
    public List<PoliticsStatus> getAllPolitics(){
        return politicsStatusService.list();
    }
    @ApiOperation("获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDep(){
        return departmentService.list();
    }
    @ApiOperation("获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJobLevel(){
        return joblevelService.list();
    }
    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPosition(){
        return positionService.list();
    }
    @ApiOperation("获取工号")
    @GetMapping("/workID")
    public String getWorkId(){
        return employeeService.getWorkId();
    }
    @ApiOperation("添加员工")
    @PostMapping("/")
    public ResultVo addEmp(@RequestBody Employee employee){
        System.out.println(employee);
        return employeeService.addEmp(employee);
    }
    @ApiOperation("更新员工")
    @PutMapping("/")
    public ResultVo updEmp(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return ResultVo.success("更新成功");
        }
        return ResultVo.error("更新失败");
    }
    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public ResultVo delEmp(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return ResultVo.success("删除成功");
        }
        return ResultVo.error("删除失败");
    }
    @ApiOperation("导出员工数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmp(HttpServletResponse response){
        //得到数据
        List<Employee> employeeList = employeeService.getEmployee(null);

        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employeeList);
        ServletOutputStream outputStream=null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation("获取导入模板")
    @GetMapping(value = "/exportMB")
    public void exportMB(HttpServletResponse response) throws IOException {
        File directory = new File("src/main/resources");
        String reportPath = directory.getCanonicalPath();
        String resource =reportPath + "/template/导入模板.xls";
        File file = new File("C:\\Users\\96522\\Desktop\\导入模板.xls");
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode("导入模板.xls","UTF-8"));
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public ResultVo importEmp(MultipartFile file){
        ImportParams params = new ImportParams();
        //标题行
        params.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            for (Employee employee : list) {
                //民族id
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌id
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //部门id
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                //职称id
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //职位id
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
                employee.setSalaryId(1);
            }
            if (employeeService.saveBatch(list)){
                return ResultVo.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVo.error("导入失败");
    }
}

